import { defineStore } from 'pinia'
import axios from 'axios'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    user: null,
    role: null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.role === 'admin'
  },
  
  actions: {
    setToken(token) {
      this.token = token
      setToken(token)
    },
    
    setUser(user) {
      this.user = user
      this.role = user?.role
    },
    
    clearUser() {
      this.token = null
      this.user = null
      this.role = null
      removeToken()
    },
    
    async login(loginData) {
      try {
        // 调用后端登录接口，替换成你实际的登录API地址
        const response = await axios.post('/api/users/login/', loginData)
        
        const { user, access, refresh } = response.data
        
        // 保存token
        this.setToken(access)
        // 保存用户信息
        this.setUser(user)
        
        // 你可以把refresh token存本地或store里，视需求而定
        
        return response.data  // 返回完整数据，方便调用处使用
      } catch (error) {
        // 你可以把后端错误信息抛出去
        throw new Error(error.response?.data?.detail || '登录失败')
      }
    },
    
    logout() {
      this.clearUser()
    }
  }
})
